import {
  Input,
  Output,
  ViewChild,
  ElementRef,
  Component,
  OnInit,
  OnChanges,
  AfterViewInit,
  SimpleChanges,
  EventEmitter,
  ViewEncapsulation,
  ChangeDetectionStrategy
} from '@angular/core';
import BScroll from '@better-scroll/core';
import ScrollBar from '@better-scroll/scroll-bar';
import MouseWheel from '@better-scroll/mouse-wheel';
import { Song } from '@services/data-types/common.type';
import { timer } from 'rxjs';
import { BaseLyricLine } from '@share/wyy-ui/wyy-player/wyy-player-panel/wyy-lyric';

BScroll.use(ScrollBar);
BScroll.use(MouseWheel);

@Component({
  selector: 'app-wyy-scroll',
  template: `<div class="wyy-scroll" #wrap>
    <ng-content></ng-content>
  </div>`,
  styles: ['.wyy-scroll {width: 100%;height: 100%; overflow: hidden;}'],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class WyyScrollComponent implements OnInit, AfterViewInit, OnChanges {
  private bs: BScroll;
  @Input() data: BaseLyricLine[] | Song[];
  @Input() refreshDelay = 50;
  @Output() private scrollEnd = new EventEmitter<number>();
  @ViewChild('wrap', { static: true }) private wrapRef: ElementRef;
  constructor(readonly el: ElementRef) { }

  ngOnInit() {}
  ngAfterViewInit() {
    this.bs = new BScroll(this.wrapRef.nativeElement, {
      scrollBar: {
        interactive: true
      },
      mouseWheel: {}
    });
    this.bs.on('scrollEnd', ({ y }) => this.scrollEnd.emit(y));
  }
  ngOnChanges(changes: SimpleChanges) {
    if (changes.data) {
      this.refreshScroll();
    }
  }
  private refresh() {
    this.bs.refresh();
  }
  refreshScroll() {
    timer(this.refreshDelay).subscribe(() => {
      this.refresh();
    });
  }
  scrollTo(...args) {
    this.bs.scrollTo.apply(this.bs, args);
  }
  scrollToElement(...args) {
    this.bs.scrollToElement.apply(this.bs, args);
  }
}
